﻿Imports DotNetNuke.Common.Globals
Imports DotNetNuke.Entities.Portals
Imports DotNetNuke.Services
Imports DotNetNuke.Services.Search
Imports DotNetNuke.Services.FileSystem
Imports DotNetNuke.Security.Permissions
Imports System.Data
Imports Aricie.DNN.Settings
Imports Aricie.DNN.Modules.LuceneSearch.Business
Imports System.IO
Imports Aricie.DNN.Modules.LuceneSearch.Settings

Namespace Aricie.DNN.Modules.LuceneSearch.ModuleProviders

    Public Class StandAloneDocumentProvider
        Implements ILuceneFieldGlossary
        Implements ILuceneStandAloneProgressiveSearchable

        Public Function GetSearchItems(ByVal portalId As Integer) As SearchItemInfoCollection Implements ILuceneStandAloneSearchable.GetSearchItems
            Dim settings As LucenePortalSettings = SettingsController.GetModuleSettings(Of LucenePortalSettings)(SettingsScope.PortalSettings, portalId)
            Dim toReturn As New SearchItemInfoCollection
            If settings.EnabledIndexingDocuments Then
                Dim fileCtlr As New FileController
                Dim folderCtlr As New FolderController

                For Each _folderId As String In settings.IndexedFolderIdList
                    Dim _folder As FolderInfo = folderCtlr.GetFolderInfo(portalId, _folderId)
                    If Not _folder Is Nothing Then
                        'On récupère tous les fichiers du dossiers
                        Dim _reader As IDataReader = fileCtlr.GetFiles(portalId, _folder.FolderID)

                        'On récupère les permissions du dossier afin d'alimenter les permissions de chacun des items
                        Dim authorizedUserIds, authorizedRoleIds As New List(Of Integer)
                        FillAuthorizedIdsList(portalId, _folder.FolderPath, authorizedRoleIds, authorizedUserIds)

                        Dim AllFiles = DotNetNuke.Common.Utilities.CBO.FillCollection(Of DotNetNuke.Services.FileSystem.FileInfo)(_reader)
                        For Each fi As DotNetNuke.Services.FileSystem.FileInfo In AllFiles
                            If fi IsNot Nothing AndAlso settings.IndexedDocExtensionsList.Contains(fi.Extension.ToLowerInvariant) Then
                                toReturn.Add(GetSearchItemFromFileId(fi, authorizedUserIds, authorizedRoleIds))
                            End If
                        Next
                        'While _reader.Read

                        '    Dim fi As FileSystem.FileInfo = fileCtlr.GetFile(_reader("FileName"), portalId, _folder.FolderID)
                        '    If fi IsNot Nothing AndAlso settings.IndexedDocExtensionsList.Contains(fi.Extension.ToLowerInvariant) Then
                        '        toReturn.Add(GetSearchItemFromFileId(fi, authorizedUserIds, authorizedRoleIds))
                        '    End If
                        'End While
                        '_reader.Close()
                    End If
                Next
            End If
            Return toReturn

        End Function

        Public Sub UpgradeSearchItem(portalId As Integer, ByRef searchItem As Business.LuceneSearchItemInfo) Implements ILuceneSearchableUpgrade.UpgradeSearchItem
            Dim FileCtrlr As New FileController()
            Dim fi As FileSystem.FileInfo = FileCtrlr.GetFileById(searchItem.ItemId, portalId)
            'Récupération du contenu du document
            searchItem.AdditionalFields = DocumentController.GetDocumentFromFile(fi.PhysicalPath, True)
            ' and that's all
        End Sub

        Public Function GetFieldDefinitions() As System.Collections.Generic.IList(Of Business.FieldDefinition) Implements Business.ILuceneFieldGlossary.GetFieldDefinitions
            Return Nothing
        End Function

        Private Shared Sub FillAuthorizedIdsList(ByVal portalId As Integer, ByVal folderPath As String, ByRef authRoleIds As List(Of Integer), ByRef authUserIds As List(Of Integer))
            Dim folderPermCtlr As New FolderPermissionController
            Dim folderPermCollec As FolderPermissionCollection
            folderPermCollec = folderPermCtlr.GetFolderPermissionsCollectionByFolderPath(portalId, folderPath)
            If Not folderPermCollec Is Nothing Then
                For Each item As FolderPermissionInfo In folderPermCollec
                    If item.PermissionKey = "READ" Then
                        If Not String.IsNullOrEmpty(item.RoleName) Then
                            authRoleIds.Add(item.RoleID)
                        ElseIf Not String.IsNullOrEmpty(item.Username) Then
                            authUserIds.Add(item.UserID)
                        End If
                    End If
                Next
            End If
        End Sub


        Protected Friend Shared Function GetSearchItemFromFileId(FI As DotNetNuke.Services.FileSystem.FileInfo, AuthorizedUserIds As List(Of Integer), AuthorizedRoleIds As List(Of Integer)) As LuceneSearchItemInfo
            Dim searchItem As New LuceneSearchItemInfo(FI.PortalId)
            searchItem.Title = Path.GetFileNameWithoutExtension(FI.PhysicalPath)
            searchItem.ItemType = Path.GetExtension(FI.PhysicalPath).Substring(1)
            searchItem.ItemGroup = "Document"
            searchItem.ItemId = FI.FileId
            searchItem.ModuleId = -1
            'On affecte les permissions à l'item à indexer
            searchItem.TabId = -1
            searchItem.InheritModuleViewPermissions = False
            searchItem.ItemUserRoleIds = AuthorizedUserIds
            searchItem.ItemViewRoleIds = AuthorizedRoleIds
            'On considère comme date de publication la dernière date de modificaiton du fichier
            searchItem.PubDate = File.GetLastWriteTime(FI.PhysicalPath)
            searchItem.SearchKey = String.Format("DNNFileId-{0}", FI.FileId)
            searchItem.GUID = String.Format("DNNFileId={0}", FI.FileId)
            searchItem.ForcedUrl = FI.PhysicalPath.Substring(FI.PhysicalPath.ToLowerInvariant.IndexOf("portals") - 1).Replace("\", "/")

            Return searchItem
        End Function

        Protected Friend Shared Function GetSearchItemFromFileId(FI As DotNetNuke.Services.FileSystem.FileInfo) As LuceneSearchItemInfo
            Dim UserIds As New List(Of Integer)
            Dim RolesIds As New List(Of Integer)
            FillAuthorizedIdsList(FI.PortalId, FI.FolderId, UserIds, RolesIds)

            Return GetSearchItemFromFileId(FI, UserIds, RolesIds)
        End Function


    End Class

End Namespace